package com.beyondsoft.mcms.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.common.DateUtil;
import com.beyondsoft.mcms.common.ExcelHandlerFactory;
import com.beyondsoft.mcms.common.ExcelImportService;
import com.beyondsoft.mcms.common.ValidateUtil;
import com.beyondsoft.mcms.domain.Category;
import com.beyondsoft.mcms.domain.Fee;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;
import com.beyondsoft.mcms.service.FeeService;
import com.beyondsoft.mcms.service.MemberInfoService;

@RequestMapping("/excelprocess/**")
@Controller
public class ExcelProcessController {

	@Autowired
	MemberInfoService memberInfoService;

	@Autowired
	FeeService feeService;

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
	}

	@RequestMapping(params = "importtype")
	public String index(@RequestParam(value = "importtype") String importtype, Model uiModel, HttpServletRequest request) {

		if (Constants.IMPORT_FILE_TYPE_MEMBER == Long.valueOf(importtype)) {
			uiModel.addAttribute("label_import_type", "label_excelprocess_import_memberinfos");
		} else if (Constants.IMPORT_FILE_TYPE_FEE == Long.valueOf(importtype)) {
			uiModel.addAttribute("label_import_type", "label_excelprocess_import_fees");
		}

		uiModel.addAttribute("importtype", importtype);
		return "excelprocess/index";
	}

	@RequestMapping(value = "uploaddata", method = RequestMethod.POST)
	public String uploaddata(@RequestParam("fileContent") MultipartFile fileContent, Model uiModel,
			HttpServletRequest request) throws Exception {

		String importtype = request.getParameter("importtype");
		String actiontype = request.getParameter("actiontype");
		StringBuffer returnMsg = new StringBuffer("");

		ExcelImportService service = ExcelHandlerFactory.CreateExcelHandler(fileContent.getOriginalFilename());
		if (service == null) {
			returnMsg.append("请上传.xls或.xlsx格式的Excel文件！");
			uiModel.addAttribute("returnMsg", returnMsg.toString());
			return index(importtype, uiModel, request);
		}

		List<Map<String, Object>> importMapList = null;
		try {
			importMapList = service.importExcel(fileContent.getInputStream()).getReturnObj();
			if (importMapList == null) {
				returnMsg.append("解析导入文件异常，请重试或检查导入模板文件！");
				uiModel.addAttribute("returnMsg", returnMsg.toString());
				return index(importtype, uiModel, request);
			}
		} catch (Exception e) {
			returnMsg.append("解析导入文件异常，请重试或检查导入模板文件！");
			e.printStackTrace();
			uiModel.addAttribute("returnMsg", returnMsg.toString());
			return index(importtype, uiModel, request);
		}

		if (importMapList.size() == 0) {
			returnMsg.append("导入文件没有数据,请录入！");
			uiModel.addAttribute("returnMsg", returnMsg.toString());
			return index(importtype, uiModel, request);
		}

		String validationMessages = "";
		if (Long.valueOf(importtype) == Constants.IMPORT_FILE_TYPE_MEMBER) {
			if (importMapList.get(0).size() < 17) {
				returnMsg.append("列数不能小于 17 ，请使用正确的导入模板！");
				uiModel.addAttribute("returnMsg", returnMsg.toString());
				return index(importtype, uiModel, request);
			}
			validationMessages = validateMemberInfoes(importMapList, actiontype);

		} else if (Long.valueOf(importtype) == Constants.IMPORT_FILE_TYPE_FEE) {
			if (importMapList.get(0).size() < 5 || importMapList.get(0).size() > 6) {
				returnMsg.append("列数不能小于 5 且不能大于 6 ，请使用正确的导入模板！");
				uiModel.addAttribute("returnMsg", returnMsg.toString());
				return index(importtype, uiModel, request);
			}
			validationMessages = validateFees(importMapList, actiontype);
		}

		uiModel.addAttribute("returnMsg", validationMessages);
		return index(importtype, uiModel, request);

	}

	private String validateMemberInfoes(List<Map<String, Object>> importMapList, String actiontype) {
		StringBuffer returnMsg = new StringBuffer();

		int m = 0; // success number
		int n = 0; // failure number
		int k = 0; // import number

		for (int i = 0; i < importMapList.size(); i++) {
			Map map = importMapList.get(i);

			if (null != map && map.size() > 0) {
				StringBuffer errorMsg = new StringBuffer("");
				int key = 0;

				String username = (String) map.get(String.valueOf(key++));
				if (null == username || "".equals(username.trim())) {
					errorMsg.append("<br/>用户名不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isUsername(username.trim())) {
					errorMsg.append("<br/>用户名格式错误 [" + (i + 2) + "," + key + "]");
				} else if (CommonUtils.usernameExisted(username)) {
					errorMsg.append("<br/>用户名已存在 [" + (i + 2) + "," + key + "]");

				}

				String password = (String) map.get(String.valueOf(key++));
				if (null == password || "".equals(password.trim())) {
					errorMsg.append("<br/>密码不能为空 [" + (i + 2) + "," + key + "]");
				}

				String memberName = (String) map.get(String.valueOf(key++));
				if (null == memberName || "".equals(memberName.trim())) {
					errorMsg.append("<br/>会员名称不能为空 [" + (i + 2) + "," + key + "]");
				} else if (CommonUtils.memberNameExisted(memberName)) {
					errorMsg.append("<br/>会员名称已存在 [" + (i + 2) + "," + key + "]");
				}

				String businessType = (String) map.get(String.valueOf(key++));
				Item businessItem = null;
				if (null == businessType || "".equals(businessType.trim())) {
					errorMsg.append("<br/>行业类型不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isID(businessType.trim())) {
					errorMsg.append("<br/>行业类型必须是正整数 [" + (i + 2) + "," + key + "]");
				} else {
					List<Item> items = Item.findItemsByCategoryAndIsValid(
							Category.findCategory(Constants.BUSINESS_TYPE), true).getResultList();
					businessItem = Item.findItem(Long.valueOf(businessType.trim()));
					if (!items.contains(businessItem)) {
						errorMsg.append("<br/>行业类型取值不在范围内 [" + (i + 2) + "," + key + "]");
					}
				}

				String adress = (String) map.get(String.valueOf(key++));
				// if (null == adress || "".equals(adress.trim())) {
				// errorMsg.append("<br/>会员地址不能为空 [" + (i + 2) + "," + key +
				// "]");
				// }

				String delegateName = (String) map.get(String.valueOf(key++));
				if (null == delegateName || "".equals(delegateName.trim())) {
					errorMsg.append("<br/>入会代表不能为空 [" + (i + 2) + "," + key + "]");
				}

				String delegatePosition = (String) map.get(String.valueOf(key++));
				if (null == delegatePosition || "".equals(delegatePosition.trim())) {
					errorMsg.append("<br/>入会代表职务不能为空 [" + (i + 2) + "," + key + "]");
				}

				String delegatePhone = (String) map.get(String.valueOf(key++));
				if (null == delegatePhone) {
					delegatePhone = "";
				}

				if (null != delegatePhone && (delegatePhone.trim().length() > 0)) {
					if (!ValidateUtil.isPhone(delegatePhone.trim())) {
						errorMsg.append("<br/>入会代表电话格式错误 [" + (i + 2) + "," + key + "]");
					}
				}

				String delegateMobile = (String) map.get(String.valueOf(key++));
				if (null == delegateMobile || "".equals(delegateMobile.trim())) {
					errorMsg.append("<br/>入会代表手机号不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isMobile(delegateMobile.trim())) {
					errorMsg.append("<br/>入会代表手机格式错误 [" + (i + 2) + "," + key + "]");
				}

				String delegateEmail = (String) map.get(String.valueOf(key++));
				if (null == delegateEmail || "".equals(delegateEmail.trim())) {
					errorMsg.append("<br/>入会代表 Email 不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isEmail(delegateEmail.trim())) {
					errorMsg.append("<br/>入会代表 Email 格式错误 [" + (i + 2) + "," + key + "]");
				}

				String delegateMicroMessage = (String) map.get(String.valueOf(key++));
				if (null == delegateMicroMessage) {
					delegateMicroMessage = "";
				}

				String contactName = (String) map.get(String.valueOf(key++));
				if (null == contactName) {
					contactName = "";
				}
				
				String contactMobile = (String) map.get(String.valueOf(key++));
				if (null == contactMobile) {
					contactMobile = "";
				}
				if (contactMobile!=null && contactMobile.trim().length()>0) {
					if (!ValidateUtil.isMobile(contactMobile.trim())) {
						errorMsg.append("<br/>联系人手机格式错误 [" + (i + 2) + "," + key + "]");
					}
				}

				String contactPhone = (String) map.get(String.valueOf(key++));
				if (null == contactPhone) {
					contactPhone = "";
				}
				if (contactPhone!=null && contactPhone.trim().length()>0) {
					if (!ValidateUtil.isPhone(contactPhone.trim())) {
						errorMsg.append("<br/>联系人电话格式错误 [" + (i + 2) + "," + key + "]");
					}
				}

				String contactEmail = (String) map.get(String.valueOf(key++));
				if (null == contactPhone) {
					contactPhone = "";
				}
				if (contactEmail!=null && contactEmail.trim().length()>0) {
					if (!ValidateUtil.isEmail(contactEmail.trim())) {
						errorMsg.append("<br/>联系人 Email 格式错误 [" + (i + 2) + "," + key + "]");
					}
				}

				String contactMicroMessage = (String) map.get(String.valueOf(key++));
				if (null == contactMicroMessage) {
					contactMicroMessage = "";
				}

				String positionType = (String) map.get(String.valueOf(key++));
				Item positionItem = null;
				if (null == positionType || "".equals(positionType.trim())) {
					errorMsg.append("<br/>协会职位不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isID(positionType.trim())) {
					errorMsg.append("<br/>协会职位必须是正整数 [" + (i + 2) + "," + key + "]");
				} else {
					List<Item> items = Item.findItemsByCategoryAndIsValid(
							Category.findCategory(Constants.POSITION_TYPE), true).getResultList();
					positionItem = Item.findItem(Long.valueOf(positionType.trim()));
					if (!items.contains(positionItem)) {
						errorMsg.append("<br/>协会职位数据不在范围内 [" + (i + 2) + "," + key + "]");
					}
				}

				if ("".equals(errorMsg.toString().trim())) {
					m++;

					if (actiontype.equals("import")) {
						MemberInfo memberInfo = new MemberInfo();
						memberInfo.setUsername(username.trim());
						memberInfo.setPassword(password.trim());
						memberInfo.setMemberName(memberName.trim());
						memberInfo.setBusinessType(businessItem);
						memberInfo.setAdress(adress.trim());
						memberInfo.setDelegateName(delegateName.trim());
						memberInfo.setDelegatePosition(delegatePosition.trim());
						memberInfo.setDelegatePhone(delegatePhone.trim());
						memberInfo.setDelegateMobile(delegateMobile.trim());
						memberInfo.setDelegateEmail(delegateEmail.trim());
						memberInfo.setDelegateMicroMessage(delegateMicroMessage.trim());
						memberInfo.setContactName(contactName.trim());
						memberInfo.setContactMobile(contactMobile.trim());
						memberInfo.setContactPhone(contactPhone.trim());
						memberInfo.setContactEmail(contactEmail.trim());
						memberInfo.setContactMicroMessage(contactMicroMessage.trim());
						memberInfo.setPositionType(positionItem);

						memberInfo.setCreatedBy(CommonUtils.getCurrentUsername());
						memberInfo.setRigesterDate(new Date());
						memberInfoService.saveMemberInfo(memberInfo);
						k++;

					}
				} else {
					returnMsg.append(errorMsg.toString());
					errorMsg.setLength(0);
					n++;
				}

			}
		}

		String sumMessage = "<br/>校验通过的记录数:" + m + "<br/>校验失败的记录数:" + n + "<br/>成功导入的记录数:" + k;
		return sumMessage + returnMsg.toString();
	}

	private String validateFees(List<Map<String, Object>> importMapList, String actiontype) {

		int m = 0; // success number
		int n = 0; // failure number
		int k = 0; // import number

		StringBuffer returnMsg = new StringBuffer();
		for (int i = 0; i < importMapList.size(); i++) {
			Map map = importMapList.get(i);
			if (null != map && map.size() > 0) {

				StringBuffer errorMsg = new StringBuffer("");
				int key = 0;

				String memberName = (String) map.get(String.valueOf(key++));
				if (null == memberName || "".equals(memberName)) {
					errorMsg.append("<br/>缴费人不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!CommonUtils.memberNameExisted(memberName)) {
					errorMsg.append("<br/>缴费人不存在 [" + (i + 2) + "," + key + "]");
				}

				String feeType = (String) map.get(String.valueOf(key++));
				Item feeTypeItem = null;
				if (null == feeType || "".equals(feeType)) {
					errorMsg.append("<br/>费用类型不能为空 [" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isID(feeType.trim())) {
					errorMsg.append("<br/>费用类型必须是正整数 [" + (i + 2) + "," + key + "]");
				} else {
					List<Item> items = Item.findItemsByCategoryAndIsValid(Category.findCategory(Constants.FEE_TYPE),
							true).getResultList();
					feeTypeItem = Item.findItem(Long.valueOf(feeType.trim()));
					if (!items.contains(feeTypeItem)) {
						errorMsg.append("<br/>费用类型取值不在范围内 [" + (i + 2) + "," + key + "]");
					}
				}

				String payAmount = (String) map.get(String.valueOf(key++));
				if (null == payAmount || "".equals(payAmount.trim())) {
					errorMsg.append("<br/>缴费金额不能为空[" + (i + 2) + "," + key + "]");
				} else if (!ValidateUtil.isAmount(payAmount)) {
					errorMsg.append("<br/>缴费金额格式错误 [" + (i + 2) + "," + key + "]");
				}

				String payDate = (String) map.get(String.valueOf(key++));
				if (null == payDate || "".equals(payDate.trim())) {
					errorMsg.append("<br/>缴费日期不能为空 [" + (i + 2) + "," + key + "]");
				}

				String transactor = (String) map.get(String.valueOf(key++));
				if (null == transactor || "".equals(transactor.trim())) {
					errorMsg.append("<br/>经办人不能为空 [" + (i + 2) + "," + key + "]");
				}

				String remark = (String) map.get(String.valueOf(key++));
				if (null == remark) {
					remark = "";
				}

				if ("".equals(errorMsg.toString().trim())) {
					m++;

					if (actiontype.equals("import")) {
						Fee fee = new Fee();
						fee.setPayer(MemberInfo.findMemberInfoesByMemberNameEquals(memberName).getSingleResult());
						fee.setPayStatus(Item.findItem(Constants.PAY_STATUS_CONFIRMED));
						//fee.setFeeType(feeTypeItem);
						//fee.setAmountPaid(new BigDecimal(payAmount.trim()));
						fee.setRealPayDate(DateUtil.stringToDate(payDate.trim(), "yyyy-MM-dd HH:mm:ss"));
						fee.setTransactor(transactor.trim());
						fee.setRemark(remark.trim());

						fee.setCreatedBy(CommonUtils.getCurrentUsername());
						fee.setCreateDate(new Date());
						fee.persist();
						k++;
					}
				} else {
					returnMsg.append(errorMsg.toString());
					errorMsg.setLength(0);
					n++;
				}
			}
		}

		String sumMessage = "<br/>校验通过的记录数:" + m + "<br/>校验失败的记录数:" + n + "<br/>成功导入的记录数:" + k;
		return sumMessage + returnMsg.toString();
	}

}
